﻿// 后端API基础地址
const apiBaseUrl = "'http://localhost:5075";
 

let token = localStorage.getItem('wechat_jwt');
let openid = '';

// 页面加载时检查登录状态
window.onload = () => {
    const urlParams = new URLSearchParams(window.location.search);
    const newToken = urlParams.get('token');


    alert("-----------");
    alert("newToken[" + newToken +"]");

    


    // 如果URL中有新token，存储并刷新页面
    if (newToken) {
        localStorage.setItem('wechat_jwt', newToken);
        window.history.replaceState({}, document.title, window.location.pathname);
        window.location.reload();
        return;
    }

    // 解析token显示用户信息
    if (token) {
        decodeToken();
        showLoginState(true);
    } else {
        showLoginState(false);
    }
};

// 解析JWT获取用户信息
function decodeToken() {
    try {
        const base64Url = token.split('.')[1];
        const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
        const payload = JSON.parse(decodeURIComponent(atob(base64).split('').map(c =>
            '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
        ).join('')));

        openid = payload.sub;
        document.getElementById('nickname').textContent = payload.name || '微信用户';
        document.getElementById('avatar').src = payload.Headimgurl || '';
    } catch (e) {
        console.error('解析token失败', e);
        logout();
    }
}

// 显示登录状态
function showLoginState(isLoggedIn) {
    const loginStatus = document.getElementById('loginStatus');
    const userInfo = document.getElementById('userInfo');
    const loginBtn = document.getElementById('loginBtn');
    const getInfoBtn = document.getElementById('getInfoBtn');
    const logoutBtn = document.getElementById('logoutBtn');

    if (isLoggedIn) {
        loginStatus.textContent = '已登录';
        userInfo.style.display = 'block';
        loginBtn.style.display = 'none';
        getInfoBtn.style.display = 'block';
        logoutBtn.style.display = 'block';
    } else {
        loginStatus.textContent = '未登录';
        userInfo.style.display = 'none';
        loginBtn.style.display = 'block';
        getInfoBtn.style.display = 'none';
        logoutBtn.style.display = 'none';
    }
}

// 跳转到后端授权接口
function login() {


    console.log("--------------");

    console.log("[" + `${apiBaseUrl}/api/auth/wechat-login?returnUrl=/index.html`   +  "]");

    //return;

    // window.location.href = `${apiBaseUrl}/api/auth/wechat-login?returnUrl=/index.html`;

     window.location.href = `/api/auth/wechat-login?returnUrl=/index.html`;




}

// 调用受保护接口
function getUserInfo() {
    fetch(`${apiBaseUrl}/user/info`, {
        headers: {
            'Authorization': `Bearer ${token}`
        }
    })
        .then(res => {
            if (!res.ok) throw new Error('未授权');
            return res.json();
        })
        .then(data => {
            document.getElementById('result').textContent = JSON.stringify(data);
        })
        .catch(err => {
            console.error('接口调用失败', err);
            logout();
        });
}

// 登出
function logout() {
    if (openid) {
        fetch(`${apiBaseUrl}/auth/logout?openid=${openid}`, {
            method: 'POST'
        }).catch(err => console.error('登出失败', err));
    }
    localStorage.removeItem('wechat_jwt');
    token = null;
    openid = '';
    showLoginState(false);
    document.getElementById('result').textContent = '';
}